<?php
namespace Admin\Controller;
use Think\Controller;
header("Content-Type:text/html; charset=utf-8");
class DepartmentController extends Controller {


    public function _initialize()
    {
        if(!check_login()){
            $this->error('登录状态异常,请重新登录','/Admin/Login/login');
        }
    }

    //查询Index
    public function index()
    {
        $lists = M('department')->select();

        foreach($lists as $key => $v){
            $classNum = M("class")->where(array("dep_id"=>$v['id']))->count();
            $lists[$key]['classNum']   =   $classNum;

            $usersNum = M("users")->where(array("dep_id"=>$v['id']))->count();
            $lists[$key]['usersNum']   =   $usersNum;
        }

    //      倒序 desc  正序asc
        $this->assign('lists',$lists);
        $this->display();
    }

    //系部添加
    public function depAdd()
    {
        $data['name']    =   I('post.name');
        $data['creator']    =   session('user');
        $data['add_time']   =   getTime();

        $res = M('department')->add($data);
        if($res) $this->redirect('Admin/Department/index');
        else $this->error("添加失败");
    }


    //删除数据
    public function delData()
    {
        $id     =   I('get.id');
        $table  =   I('get.table');
        $info   =   M($table)->where("id in ($id)")->find();

        $insert = M("class")->where(array('dep_id'=>$id))->select();

        if ($insert) {
            $res = 2;
        } else {
            $res    =   M($table)->where("id in ($id)")->delete();
            if($res !== false){
                if($info['pic']) unlink('.'.$info['pic']);
                if($info['mini_pic']) unlink('.'.$info['mini_pic']);
            }
        }

        echo $res;
    }

}